package Dao;

import pojo.Car;
import pojo.User;

import java.io.*;
import java.util.ArrayList;

/**
 * 用户初始化
 */
public class UserDao {
    private static ArrayList<User> users = new ArrayList<>();
    private static File file = new File(FileLocation.file + "\\User.txt");

    static {


        User user = new User("1", "1", true);
        User user1 = new User("2", "2", false);
        User user2 = new User("3", "3", false);

        users.add(user);
        users.add(user1);
        users.add(user2);
    }

    /**
     * 反序列化对象
     *
     * @return
     */
    public static ArrayList<User> getUsers() {
        FileInputStream input = null;
        ObjectInputStream oInput = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            input = new FileInputStream(file);
            oInput = new ObjectInputStream(input);
            users = (ArrayList<User>) oInput.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                oInput.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return users;
    }

    /**
     * 序列化对象
     */
    public static void setUsers() {
        FileOutputStream input = null;
        ObjectOutput oOut = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            input = new FileOutputStream(file);
            oOut = new ObjectOutputStream(input);
            oOut.writeObject(users);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                oOut.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}